package com.majiang.community.service;

import com.majiang.community.dto.PageDto;
import com.majiang.community.dto.QuestionDTO;
import com.majiang.community.mapper.QuestionMapper;
import com.majiang.community.mapper.UserMapper;
import com.majiang.community.model.Question;
import com.majiang.community.model.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yu
 * @date 2021/8/14 19:55
 */
@Service
public class QuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private UserMapper userMapper;

    public PageDto list(Integer page, Integer rows) {

        PageDto pageDto = new PageDto();
        Integer count = questionMapper.count();
        pageDto.setPageDto(count, page, rows);
        if (page < 1) {
            page = 1;
        }
        if(page > pageDto.getTotalPage()){
            page = pageDto.getTotalPage();
        }
        Integer offset = rows*(page-1);
        List<Question> list = questionMapper.list(offset, rows);
        List<QuestionDTO> questionDTOList = new ArrayList<>();
        for (Question question : list) {
            User user = userMapper.findById(question.getCreator());
            QuestionDTO questionDTO = new QuestionDTO();
            BeanUtils.copyProperties(question, questionDTO);
            questionDTO.setUser(user);
            questionDTOList.add(questionDTO);
        }
        pageDto.setQuestionDTOList(questionDTOList);

        return pageDto;
    }

    public PageDto listByUserId(Integer id, Integer page, Integer rows) {
        PageDto pageDto = new PageDto();
        Integer count = questionMapper.countByUserId(id);
        pageDto.setPageDto(count, page, rows);
        if (page < 1) {
            page = 1;
        }
        if(page > pageDto.getTotalPage()){
            page = pageDto.getTotalPage();
        }
        Integer offset = rows*(page-1);
        List<Question> list = questionMapper.listByUserId(id, offset, rows);
        List<QuestionDTO> questionDTOList = new ArrayList<>();
        for (Question question : list) {
            User user = userMapper.findById(question.getCreator());
            QuestionDTO questionDTO = new QuestionDTO();
            BeanUtils.copyProperties(question, questionDTO);
            questionDTO.setUser(user);
            questionDTOList.add(questionDTO);
        }
        pageDto.setQuestionDTOList(questionDTOList);

        return pageDto;
    }
}
